package controllers

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/client"
	"install/models"
	"net"
	"os"
	"strings"
)



type InstallController struct {
	beego.Controller
}

func (u *InstallController) Test() {


}

func (c *InstallController) Protocol() {
	c.Data["Website"] = "beego.me"
	c.Data["Email"] = "astaxie@gmail.com"
	c.TplName = "install/protocol.html"
}


func (this *InstallController) Environment() {

	//检查docker 是否安装
	version :=this.GetDockerVersion()

	//检查docker 是否可以使用
	info,err:=this.CheckDockerStatus()

	if err != nil {
		this.Data["dockerStatus"] = false
	}else{
		this.Data["dockerStatus"] = true
		this.Data["Containers"]=info.Containers
		this.Data["Images"]=info.Images
		this.Data["DockerRootDir"]=info.DockerRootDir //docker根目录
		this.Data["ServerVersion"]=info.ServerVersion//docker服务器版本
		this.Data["Driver"]=info.Driver //docker驱动
		this.Data["MemTotal"]=info.MemTotal //内存大小
		this.Data["CPUs"]=info.NCPU //cpus数量
	}


	beego.Debug(this.Data["Containers"])

	beego.Debug(version)
	//this.structToJSON(info)

	if(version !="dcokerNot"){
		this.Data["dockerVersion"] = version //docker 客户端
	}else{
		this.Data["dockerVersion"]=false
	}
	//fmt.Printf("%v\n", this.Data["dockerVersion"])
	this.TplName = "install/environment.html"

}


func (this *InstallController) BaseService() {

	this.TplName = "install/baseService.html"

}


func (this *InstallController) getClientIp() (string) {
		conn, err := net.Dial("udp", "baidu.com:80")
		if err != nil {
		fmt.Println(err.Error())
		return "Erorr"
	}
		defer conn.Close()
		return strings.Split(conn.LocalAddr().String(), ":")[0]
}

func (this *InstallController) Finishs() {

	//判断容器是否存在，如果存在直接启动

	//如果容器不存在创建容器
	imageName :="registry.cn-shenzhen.aliyuncs.com/uniappadmin/uniappadmin"
	id,err :=models.CreateContainers(imageName)
	if err ==nil{
		models.StartContainers(id)
	}
	ip:=this.getClientIp()
	//访问接口
	this.Data["uniappadmin"]= "http://"+ip+":5207"
	this.Data["service_config"]= "http://"+ip+":5212"
	this.TplName = "install/finish.html"


	this.createFile()


}
//创建文件
func (this *InstallController) createFile(){
	//Create函数也是调用的OpenFile
	file, error := os.Create("conf/install.bak")
	if error != nil {
		fmt.Println(error)
	}
	fmt.Println(file)
	file.Close()
}
func (this *InstallController) CheckDockerStatus() (types.Info, error){
	ctx := context.Background()
	var info types.Info
	cli, err := client.NewClientWithOpts(client.WithVersion("1.38"))
	if err != nil {
		return  info, err
	}

	infos,err :=  cli.Info(ctx)
	if err != nil {
		return infos, fmt.Errorf("Error reading remote info: %v", err)
	}

	return infos,nil
	//this.structToJSON(info)
	//
	//fmt.Println(info)
}
//结构体转JSON
func  (this *InstallController) structToJSON(info types.Info) {


	data, err := json.Marshal(info)

	if err != nil {

		fmt.Println("json.marshal failed, err:", err)
		return
	}

	fmt.Printf("%s\n", string(data))
}


func (this *InstallController) GetDockerVersion() string{
	cli, err := client.NewClientWithOpts(client.WithVersion("1.38"))
	if err != nil {
		return "dcokerNot"
	}
	version :=  cli.ClientVersion()
	return version

}

func (this *InstallController) List() {
	this.Ctx.Output.Body([]byte("i am list"))
}

